/**
 * 是否启用pdf，true启用,false不启用
 */
var startPdfPreview = false;
//判断浏览器版本，当浏览器是IE8并且使用控件获取文件大小报错时，提示
var browserInfo = getBrowserInfo();
/**
 * 创建DSYWidget管理器
 */
if (!window.DSYWidget) {
    window.DSYWidget = {
        Manager: {
            grid: {}
        }
    };
    window.DSYWidget = DSYWidget;
} else if (!window.DSYWidget.Manager) {
    window.DSYWidget.Manager = {
        grid: {}
    };
} else if (!window.DSYWidget.Manager.grid) {
    window.DSYWidget.Manager.grid = {};
}

/**
 * 新版图片预览弹出框
 */
function imageAfterLoad(self, fileId) {
    new Viewer(self, {
        url: 'data-original',
        navbar: false,
        zIndex: 20000,
        container: document.body,
        title: true,
        toolbar: {
            zoomIn: 1,
            zoomOut: 1,
            oneToOne: 1,
            reset: 1,
            prev: 0,
            play: 0,
            next: 0,
            rotateLeft: 1,
            rotateRight: 1,
            flipHorizontal: 1,
            flipVertical: 1
        },
        viewed: function(self) {
            var viewers = window.top.document.getElementsByClassName("viewer-toolbar");
            for(var i = 0; i < viewers.length; i++) {
                var viewer = viewers[i].firstChild;
                if(viewer.getElementsByClassName("viewer-zoom-down").length === 0 && !$(viewers[i]).is(':hidden')) {
                    var li = document.createElement("li");
                    li.setAttribute("onclick", "UploadPanel.downloadFile('" + fileId + "')")
                    li.setAttribute("class", "viewer-zoom-down");
                    li.setAttribute("title", "下载");
                    viewer.appendChild(li);
                }
            }
        }
    });
}

/**
 * IE8下附件预览
 */
function imageClick(file_id) {
    top.Ext.create('Ext.window.Window', {
        title: '图片预览',
        maximizable: true,
        modal: true, // 模式窗口，弹出窗口后屏蔽掉其他组件
        width: top.document.body.clientWidth * 0.75,
        height: top.document.body.clientHeight * 0.75,
        scrollable: true,
        items: {
            xtype: 'box', //或者xtype: 'component',
            layout: 'hbox',
            autoEl: {
                tag: 'img',    //指定为img标签
                src: '/report/third-api/uploadFile/previewReadyImage?fileId=' + file_id  //指定url路径
            }
        }
    }).show();
}

/**
 * 预览pdf文件
 */
function pdfPreviewFile(fileId, form){
    Ext.Ajax.request({
        method: 'GET',
        url: "/report/third-api/uploadFile/queryFileIsExist",
        params: {
            fileId: fileId
        },
        success: function (res) {
            var data = Ext.util.JSON.decode(res.responseText);
            if (data) {
                form = encodeURI(form);
                var href = "/report/third/pdf/web/viewerPdf.html?fileId=" + fileId + "&fileName=" + form;
                window.open(href);
            } else {
                Ext.Msg.alert('提示', "您要预览的资源不存在！" + data.message);
            }
        },
        failure: function (form, action) {
            Ext.Msg.alert('提示', "您要预览的资源不存在！" + action.result ? action.result.message : '无返回响应');
        }
    });
    // var tempWindow = window.open('/report/page/frame/loading.jsp');
    // $.post("/report/sys-manage/pdf/preview_path",{
    // 	file_id: fileId,
    // 	form: form
    // }, function(data){
    // 	tempWindow.location = data.localPath;
    // }, 'json');
}

/**
 * 创建文件上传封装对象
 */
function UploadPanel() {
    /**
     * 上传控件表头
     * @type {*[]}
     */
    this.headerJson = [
        {
            text: "操作", menuDisabled: true, sortable: false,
            renderer: function (value, cell, record, rowIndex, colIndex, store, view) {
                //上传提示信息
                var tipText = '小于' + record.data.MAXLIMIT / 1024 + 'MB';
                var tip = record.data.FILE_SUFFIX + tipText;
                //上传按钮，上层覆盖透明上传表单
                var uploadbtn = '<div title="' + tip + '" class="uploadpanel-btn uploadpanel-btn-upload">' +
                    '<form id="uploadpanel-' + view.grid.itemId + '-uploadform-' + rowIndex + '" class="uploadForm" enctype="multipart/form-data">' +
                    '<input type="submit" />' +
                    '<input type="text" name="ruleId" value=""/>' +
                    '<input type="text" name="busiId" value=""/>' +
                    '<input type="text" name="maxlimit" value=""/>' +
                    '<input type="file" name="file" itemId="' + view.grid.itemId + '" rowIndex="' + rowIndex + '" onchange="UploadPanel.uploadFile(this)"/>' +
                    '</form></div>';
                var downloadbtn = '<div class="uploadpanel-btn uploadpanel-btn-download" onclick="UploadPanel.downloadFile(\'' + record.get("FILE_ID") + '\')"></div>';
                var deletebtn = '<div class="uploadpanel-btn uploadpanel-btn-delete" onclick="UploadPanel.deleteFile(\'' + record.get("FILE_ID") + '\',\'' + record.get("RULE_ID") + '\',\'' + record.get("FILE_NAME") + '\',\'' + view.grid.itemId + '\',\'' + rowIndex + '\')"></div>';
                //根据是否可编辑，隐藏上传/删除按钮
                if (!store.editable) {
                    uploadbtn = '';
                    deletebtn = '';
                }
                var preview = ''; // 预览按钮
                //如果文件存在，隐藏上传按钮
                var fileId = record.data.FILE_ID;
                if (typeof fileId != 'undefined' && fileId != null && fileId != '') {
                    uploadbtn = ''; // 存在隐藏上传按钮
                    var form = record.data.FILE_NAME.split(".")[record.data.FILE_NAME.split(".").length - 1].toLowerCase();
                    if((form == 'pdf' || form == 'docx' || form == "doc") && startPdfPreview){
                        preview = '<div title="预览" class="uploadpanel-btn uploadpanel-btn-preview" onclick="pdfPreviewFile(\'' + fileId + '\',\'' + form + '\')"></div>';
                    }
                }else{ //根据文件id是否存在，隐藏下载按钮
                    downloadbtn = ''; // 不存在，隐藏下载按钮
                }
                return '<div class="uploadpanel-btsn">' + uploadbtn + downloadbtn + deletebtn + preview + '</div>';
            }
        },
        {text: "业务类型", dataIndex: "BUSI_TYPE", type: "string", hidden: true},
        {text: "业务规则", dataIndex: "BUSI_PROPERTY", type: "string", hidden: true},
        {text: "规则id", dataIndex: "RULE_ID", type: "string", hidden: true},
        {
            text: "上传文件名称", dataIndex: "FILE_NAME", width: 330, type: "string", cellWrap: true,
            renderer: function (data, cell, record) {
                //给文件添加超链接
                var path = record.get('FILE_PATH');
                var file_id = record.get('FILE_ID');
                //当为必选项，并且file_id为空的时候，行背景色为淡黄色
                var star = '';
                if (record.get('NULLABLE') == 'N' && (this.config.isMustUpload != false)) {
                    star = '<span class="required">✶</span>';
                    if (typeof(file_id) == "undefined" || file_id == null || file_id == '' || file_id == 'null' || file_id == '0') {
                        star = '<span class="required">✶必录附件</span>';
                    }
                }
                var form = data.split(".")[data.split(".").length - 1].toLowerCase();
                if(form == "dps" || form == "dpt" || form == "odp" || form == "otp") {
                    form = "pdf";
                }else if(form == "wps" || form == "wpt" || form == "odt" || form == "ott") {
                    form = "docx";
                }else if(form == "et" || form == "ett" || form == "ods" || form == "ots") {
                    form = "xlsx";
                }
                var image = '';
                if (form != null && form != "") {
                    image = '<image src="/report/image/file/' + form + '.png">&nbsp';
                }
                if (form == "png" || form == "jpg" || form == "jpeg") {
                    if (browserInfo["browser"] === "IE" && browserInfo["version"] === "8.0") {
                        image = "<image style='width:64px;height:64px;cursor:pointer;' onclick='imageClick(\"" + file_id + "\")' src='/report/third-api/uploadFile/previewImage?fileId=" + file_id + "'/>";
                    }else {
                        image = "<image style='width:64px;height:64px;cursor:pointer;' data-original='/report/third-api/uploadFile/previewReadyImage?fileId=" + file_id +
                            "' src='/report/third-api/uploadFile/previewImage?fileId=" + file_id + "' onload='imageAfterLoad(this, \"" + file_id + "\")' alt='" + data + "' title='" + data + "'/>";
                    }
                }
                return star + image + '<a href="javascript:void(0);" style="color:#3329ff;" onclick="UploadPanel.downloadFile(\'' + file_id + '\')">' + data + '</a>';
            }
        },
        {
            text: "附件描述", dataIndex: "FILE_DESC", width: 300, type: "string", cellWrap: true,
            renderer: function (data, cell, record) {
                //当附件id存在，并且业务规则不存在时，附件描述为：自行提交的附件
                var fild_id = record.get("FILE_ID");
                var busi_property = record.get('BUSI_PROPERTY');
                var file_name = record.get('FILE_NAME');
                if ((busi_property == null || busi_property == '' || busi_property == 'null') &&
                    (fild_id != null && fild_id != '' && fild_id != 'null' && fild_id != '0')) {
                    return data ? data : file_name;
                }
                return data;
            }
        },
        {
            text: "文件大小", dataIndex: "FILE_SIZE", width: 125, type: "string",
            renderer: function (data, cell, record) {
                if (isNaN(parseFloat(data))) {
                    return data;
                } else if (parseFloat(data) < (1024 * 1024)) {
                    return (parseFloat(data) / 1024).toFixed(2) + 'KB';
                }
                return (parseFloat(data) / (1024 * 1024)).toFixed(2) + 'MB';
            }
        },
        {
            text: "文件类型限制", dataIndex: "FILE_SUFFIX", width: 125, type: "string", hidden: true, cellWrap: true
        },
        {
            text: "文件大小限制", dataIndex: "LIMIT_SIZE", width: 125, type: "string", hidden: true,
            renderer: function (data, cell, record, rowIndex, colIndex, store, view) {
                var text = '';
                if (!record.get('RULE_ID')) {
                    var uploadConfig = UploadPanel.getConfig(view.grid.itemId).config;
                    record.data.MINLIMIT = 0;
                    record.data.MAXLIMIT = uploadConfig.file_size;
                    record.data.LIMIT_SIZE = '0-' + uploadConfig.file_size + 'KB';
                }
                if (record.data.MINLIMIT && record.data.MINLIMIT > 1) {
                    text = '大于' + record.data.MINLIMIT / 1024 + 'MB';
                }
                return text + '小于' + record.data.MAXLIMIT / 1024 + 'MB';
            }
        },
        {text: "上传状态", dataIndex: "STATUS", type: "string", hidden: true},
        {text: "文件ID", dataIndex: "FILE_ID", type: "string", hidden: true},
        {text: "文件最小值", dataIndex: "MINLIMIT", type: "int", hidden: true},
        {text: "文件最大值", dataIndex: "MAXLIMIT", type: "int", hidden: true},
        {text: "是否限制文件的类型", dataIndex: "IS_LIMITTYPE", type: "string", hidden: true},
        {text: "是否限制文件的大小", dataIndex: "IS_LIMITSIZE", type: "string", hidden: true},
        {text: "是否必须上传", dataIndex: "NULLABLE", type: "string", hidden: true}
    ];
    this.headerJson_FREE = [
        {
            xtype: 'rownumberer',
            width: 20
        },
        {
            text: "操作", menuDisabled: true, sortable: false,
            renderer: function (value, cell, record, rowIndex, colIndex, store, view) {
                var itemId = view.grid.columns[view.grid.columns.length - 1].text;
                //上传按钮，上层覆盖透明上传表单
                var uploadbtn = '<div class="uploadpanel-btn uploadpanel-btn-upload">' +
                    '<form id="uploadpanel-' + itemId + '-uploadform-' + rowIndex + '" class="uploadForm" enctype="multipart/form-data">' +
                    '<input type="submit" />' +
                    '<input type="text" name="ruleId" value=""/>' +
                    '<input type="text" name="busiId" value=""/>' +
                    '<input type="text" name="maxlimit" value=""/>' +
                    '<input type="file" name="file" itemId="' + itemId + '" rowIndex="' + rowIndex + '" onchange="UploadPanel.uploadFile(this)"/>' +
                    '</form></div>';
                var downloadbtn = '<div class="uploadpanel-btn uploadpanel-btn-download" onclick="UploadPanel.downloadFile(\'' + record.get("FILE_ID") + '\')"></div>';
                var deletebtn = '<div class="uploadpanel-btn uploadpanel-btn-delete" onclick="UploadPanel.deleteFile(\'' + record.get("FILE_ID") + '\',\'' + record.get("RULE_ID") + '\',\'' + record.get("FILE_NAME") + '\',\'' + itemId + '\',\'' + rowIndex + '\')"></div>';
                //根据是否可编辑，隐藏上传/删除按钮
                if (!store.editable) {
                    uploadbtn = '';
                    deletebtn = '';
                }
                var preview = ''; // 预览按钮
                //如果文件存在，隐藏上传按钮
                var fileId = record.data.FILE_ID;
                if (typeof fileId != 'undefined' && fileId != null && fileId != '') {
                    uploadbtn = ''; // 存在隐藏上传按钮
                    var form = record.data.FILE_NAME.split(".")[record.data.FILE_NAME.split(".").length - 1].toLowerCase();
                    if((form == 'pdf' || form == 'docx' || form == "doc") && startPdfPreview){
                        preview = '<div title="预览" class="uploadpanel-btn uploadpanel-btn-preview" onclick="pdfPreviewFile(\'' + fileId + '\',\'' + form + '\')"></div>';
                    }
                }else{ //根据文件id是否存在，隐藏下载按钮
                    downloadbtn = ''; // 不存在，隐藏下载按钮
                }
                return '<div class="uploadpanel-btsn">' + uploadbtn + downloadbtn + deletebtn + preview + '</div>';
            }
        },
        {
            text: "上传文件名称", dataIndex: "FILE_NAME", width: 330, type: "string", cellWrap: true,
            renderer: function (data, cell, record) {
                //给文件添加超链接
                var path = record.get('FILE_PATH');
                var file_id = record.get('FILE_ID');
                //当为必选项，并且file_id为空的时候，行背景色为淡黄色
                var star = '';
                if (record.get('NULLABLE') == 'N' && (this.config.isMustUpload != false)) {
                    star = '<span class="required">✶</span>';
                    if (typeof(file_id) == "undefined" || file_id == null || file_id == '' || file_id == 'null' || file_id == '0') {
                        star = '<span class="required">✶必录附件</span>';
                    }
                }
                var form = data.split(".")[data.split(".").length - 1].toLowerCase();
                if(form == "dps" || form == "dpt" || form == "odp" || form == "otp") {
                    form = "pdf";
                }else if(form == "wps" || form == "wpt" || form == "odt" || form == "ott") {
                    form = "docx";
                }else if(form == "et" || form == "ett" || form == "ods" || "ots") {
                    form = "xlsx";
                }
                var image = '';
                if (form != null && form != "") {
                    image = '<image src="/report/image/file/' + form + '.png">&nbsp';
                }
                if (form == "png" || form == "jpg" || form == "jpeg") {
                    if (browserInfo["browser"] === "IE" && browserInfo["version"] === "8.0") {
                        image = "<image style='width:64px;height:64px;cursor:pointer;' onclick='imageClick(\"" + file_id + "\")' src='/report/third-api/uploadFile/previewImage?fileId=" + file_id + "'/>";
                    }else {
                        image = "<image style='width:64px;height:64px;cursor:pointer;' data-original='/report/third-api/uploadFile/previewReadyImage?fileId=" + file_id +
                            "' src='/report/third-api/uploadFile/previewImage?fileId=" + file_id + "' onload='imageAfterLoad(this, \"" + file_id + "\")' alt='" + data + "' title='" + data + "'/>";
                    }
                }
                return star + image + '<a href="javascript:void(0);" style="color:#3329ff;" onclick="UploadPanel.downloadFile(\'' + file_id + '\')">' + data + '</a>';
            }
        },
        {
            text: "文件大小", dataIndex: "FILE_SIZE", width: 125, type: "string",
            renderer: function (data, cell, record) {
                if (isNaN(parseFloat(data))) {
                    return data;
                } else if (parseFloat(data) < (1024 * 1024)) {
                    return (parseFloat(data) / 1024).toFixed(2) + 'KB';
                }
                return (parseFloat(data) / (1024 * 1024)).toFixed(2) + 'MB';
            }
        },
        {
            text: "文件类型限制", dataIndex: "FILE_SUFFIX", width: 125, type: "string", cellWrap: true, hidden: true
        },
        {
            text: "文件大小限制", dataIndex: "LIMIT_SIZE", width: 125, type: "string", hidden: true,
            renderer: function (data, cell, record, rowIndex, colIndex, store, view) {
                var text = '';
                if (!record.get('RULE_ID')) {
                    var uploadConfig = UploadPanel.getConfig(view.grid.itemId).config;
                    record.data.MINLIMIT = 0;
                    record.data.MAXLIMIT = uploadConfig.file_size;
                    record.data.LIMIT_SIZE = '0-' + uploadConfig.file_size + 'KB';
                }
                if (record.data.MINLIMIT && record.data.MINLIMIT > 1) {
                    text = '大于' + record.data.MINLIMIT / 1024 + 'MB';
                }
                return text + '小于' + record.data.MAXLIMIT / 1024 + 'MB';
            }
        },
        {text: "上传状态", dataIndex: "STATUS", type: "string", hidden: true}
    ];
    this.config = {
        file_type: null,//系统变量文件类型
        file_size: null,//系统变量文件大小
        file_store_mode: null,//系统变量文件储存方式
        busiType: null,//busi_type业务类型
        busiId: null,//busi_id业务ID
        busiProperty: '%',//业务规则
        editable: true,//是否可对附件进行操作
        addfileable: true,//是否可对附件进行新增行操作
        headerType: '',//表头类型：默认为headerJson,FREE：为headerJson_FREE，DIY：为用户自定义
        grid: null,//表格
        gridConfig: {//表格配置
            itemId: 'UploadGrid',
            headerConfig: {
                headerJson: this.headerJson,
                columnAutoWidth: false
            },
            height: '100%',
            dataUrl: '/report/third-api/uploadFile/list',
            pageConfig: {
                enablePage: false
            },
            plugins: [
                {
                    ptype: 'cellediting',
                    clicksToEdit: 1,
                    pluginId: 'fileGrid_cellediting',
                    clicksToMoveEditor: 1,
                    listeners: {
                        beforeedit: function (editor, context) {
                            if(!context.grid.editable) {
                                return false;
                            }
                            if(!context.record.data.FILE_ID) {
                                Ext.toast({
                                    html: "请先上传附件！",
                                    closable: false,
                                    align: 't',
                                    slideInDuration: 400,
                                    minWidth: 400
                                });
                                return false;
                            }
                        }
                    }
                }
            ]
        }
    };
    this.addUploadButton = function (config) {//根据是否有规则设置按钮
        var headerType = config.headerType;
        var itemId = config.gridConfig.itemId;
        var file_size = config.file_size;
        var file_type = config.file_type;
        var uploadbtn = '<div class="uploadpanel-btn uploadpanel-btn-upload">' +
            '<form id="form-' + itemId + '" class="uploadForm" enctype="multipart/form-data">' +
            '<input type="submit" name="btn_add"/>' +
            '<input type="text" name="ruleId" value=""/>' +
            '<input type="text" name="busiId" value=""/>' +
            '<input type="text" name="maxlimit" value=""/>' +
            '<input type="submit" /><input type="file" itemId="' + itemId + '" name="file" onchange="UploadPanel.uploadFile(this,\'form-' + itemId + '\')"/>' +
            '</form></div>';
        return [
            headerType == 'FREE' ? {
                xtype: 'tbtext',
                name: 'btn_add',
                text: '<div class="uploadpanel-btsn">&nbsp点击图标上传附件' + uploadbtn + '</div>'
            } : {
                xtype: 'button',
                text: '增行',
                name: 'btn_add',
                icon: '/report/image/sysbutton/add.png',
                handler: function (btn) {
                    var file_size = UploadPanel.getConfig(btn.up('grid').itemId).config.file_size;
                    var file_type = UploadPanel.getConfig(btn.up('grid').itemId).config.file_type;
                    btn.up('grid').insertData(null, {
                        FILE_ID: null,
                        FILE_NAME: null,
                        LIMIT_SIZE: '0-' + file_size + 'KB',
                        MINLIMIT: 0,
                        MAXLIMIT: file_size,
                        FILE_SUFFIX: file_type
                    });
                }
            }
        ];
    }
    this.create = function (config_param) {//设置行背景色
        if (typeof config_param.busiId == 'undefined' || config_param.busiId == null || config_param.busiId.length <= 0) {
            // Ext.Msg.alert('提示', '附件缺失唯一标识！');
        }
        //根据用户定义类型
        if (config_param.headerType != '') {
            if (config_param.headerType == 'FREE') {
                this.headerJson_FREE.push({dataIndex: 'ITEMID', text: config_param.gridConfig.itemId, hidden: true});
                this.config.gridConfig.headerConfig.headerJson = this.headerJson_FREE;
            } else if (config_param.headerType == 'DIY') {
                this.config.gridConfig.headerConfig.headerJson = null;
            }
        }
        //继承用户参数
        this.config = $.extend(true, {}, this.config, config_param);
        //发送同步请求，获取系统变量
        if (this.config.file_type == null && this.config.file_size == null) {
            var file_type = this.config.file_type;
            var file_size = this.config.file_size;
            var file_store_mode = this.config.file_store_mode;
            $.ajax({
                type: "POST",
                url: '/report/third-api/api/sys-data/paramValueAll',
                async: false, //设为false就是同步请求
                cache: false,
                success: function (jsonData) {
                    // var data = JSON.parse(jsonData).data;
                    file_type = jsonData['DEBT_FILE_TYPE'];
                    file_size = jsonData['DEBT_FILE_SIZE'];
                    file_store_mode = jsonData['FILE_STORE_MODE'];
                }
            });
            this.config.file_type = file_type;
            this.config.file_size = file_size;
            this.config.file_store_mode = file_store_mode;
        }
        //生成表格tbar
        if (typeof this.config.gridConfig.tbar == 'undefined' || this.config.gridConfig.tbar == null) {
            this.config.gridConfig.tbar = [];
        }
        //设置表格参数
        this.config.gridConfig.params = $.extend({
            busiType: this.config.busiType,
            ruleIds: !!this.config.ruleIds ? this.config.ruleIds.join(",") : '',
            isFilter: this.config.isFilter,
            busiId: this.config.busiId,
            busiProperty: this.config.busiProperty,
            editable: this.config.editable
        }, this.config.gridConfig.params);
        if(!!this.config.filterParam) {
            this.config.gridConfig.params.filterParam = this.config.filterParam;
        }
        //添加按钮
        this.config.gridConfig["tbar"] = new UploadPanel().addUploadButton(this.config);
        //判断是否是无规则的，如果是无规则，则列自适应
        if (config_param.headerType == 'FREE') {
            this.config.gridConfig.headerConfig.columnAutoWidth = true;
        }
        //判断是否增加表格扩展字段
        if(!!config_param.addHeaders) {
            var addFields = "";
            var saveFields = [];
            var fieldList = "BUSI_PROPERTY_DESC,FILE_NAME FILE_NAME,FILE_SIZE FILE_SIZE,FILE_PATH FILE_PATH,UPLOAD_USER,UPLOAD_TIME,FILE_ID FILE_ID,AD_CODE,AD_NAME,AG_CODE,AG_NAME";
            for(var i = 0; i < config_param.addHeaders.length; i++) {
                if(fieldList.indexOf(config_param.addHeaders[i].dataIndex) == -1) {
                    addFields += "B." + config_param.addHeaders[i].dataIndex + ",";
                }
                saveFields.push(config_param.addHeaders[i].dataIndex);
                if(!!config_param.addHeaders[i].index) {
                    this.config.gridConfig.headerConfig.headerJson.splice(config_param.addHeaders[i].index, 0, config_param.addHeaders[i]);
                }else {
                    this.config.gridConfig.headerConfig.headerJson.push(config_param.addHeaders[i]);
                }
            }
            this.config.gridConfig.params["addFields"] = addFields;
            this.config.gridConfig.params["saveFields"] = saveFields;
        }
        //创建表格
        this.config.grid = DSYGrid.createGrid(this.config.gridConfig);
        //追加是否可编辑属性到表格和数据集中
        this.config.grid.editable = this.config.editable;
        this.config.grid.getStore().editable = this.config.editable;
        if (!this.config.editable || !this.config.addfileable) {
            //如果不可编辑，隐藏新增按钮
            var btn_add = this.config.grid.down('[name="btn_add"]');
            if (btn_add) {
                btn_add.destroy();
            }
            //如果工具栏无其他元素，隐藏tbar
            var tbar = this.config.grid.getDockedItems('toolbar[dock="top"]');
            for (var i = 0; i < tbar.length; i++) {
                if (!tbar[i].items || tbar[i].items.length <= 0) {
                    tbar[i].destroy();
                }
            }
        }
        DSYWidget.Manager.grid[this.config.gridConfig.itemId] = this;
        return this.config.grid;
    };
    /**
     * 计算文件大小，返回文件大小值，单位K
     * @param target
     * @returns {number}
     */
    function getFileSize(target) {
        var isIE = /msie/i.test(navigator.userAgent) && !window.opera;
        var fs = 0;
        if (isIE && !target.files) {
            var filePath = target.value;
            var fileSystem = new ActiveXObject("Scripting.FileSystemObject");
            var file = fileSystem.GetFile(filePath);
            fs = file.Size;
        } else if (target.files && target.files.length > 0) {
            fs = target.files[0].size;
        } else {
            fs = 0;
        }
        if (fs > 0) {
            fs = fs / 1024;
        }
        return fs;
    }
}

/**
 * 保存额外字段
 * @param config
 */
UploadPanel.saveExtraField = function(itemId, isReload) {
    var grid = DSYGrid.getGrid(itemId);
    var store = grid.getStore();
    var fieldList = store.getProxy().extraParams["saveFields"];
    if(!fieldList) {
        return;
    }
    var items = grid.getStore().data.items;
    var params = [];
    var fields = fieldList;
    for(var i = 0; i < items.length; i++) {
        var param = {};
        for(var j = 0; j < fieldList.length; j++) {
            if(!!fieldList[j]) {
                var field = fieldList[j];
                param[field] = items[i].data[field];
            }
        }
        param["FILE_ID"] = items[i].data["FILE_ID"];
        params.push(param);
    }
    if(fields.indexOf("FILE_ID") == -1) {
        fields.push("FILE_ID");
    }
    $.ajax({
        type: "post",
        url:"/report/sys-manage/file/extra_field/save",
        data:{
            params: Ext.util.JSON.encode(params),
            fields: fields.join(",")
        },
        dataType:"json",
        async:false,// 同步
        success: function(data) {
            if(!data.SUCCESS) {
                Ext.MessageBox.alert("提示", "附件信息保存失败！");
            }else if(!!isReload){
                store.reload();
            }
        }
    });
}
/**
 * 提交上传信息
 * @param btn 上传按钮
 */
UploadPanel.uploadFile = function (btn, formId) {
    var record = {};
    var uploadPanelConfig = {};
    var rowIndex = $(btn).attr('rowindex');
    //无规则特殊处理特殊处理会传过来itemId的值，这里判断如果没有传值则走默认的逻辑
    itemId = $(btn).attr('itemid');
    if (!formId) {
        record = DSYGrid.getGrid(itemId).getStore().getAt(rowIndex);
        uploadPanelConfig = UploadPanel.getConfig(itemId);
    } else {
        uploadPanelConfig = UploadPanel.getConfig(itemId);
        record = {
            "data": {
                "MAXLIMIT": uploadPanelConfig.config.file_size,
                "MINLIMIT": 0,
                "FILE_SUFFIX": uploadPanelConfig.config.file_type,
                "IS_LIMITSIZE": undefined,
                "RULE_ID": ""
            }
        };
    }
    //对上传文件的校验（文件类型）
    if (!UploadPanel.checkFileType(btn, record, uploadPanelConfig.config.file_type)) {
        return false;
    }
    try {
        //对上传文件的校验（文件大小）
        if (!UploadPanel.checkFileSize(btn, record, uploadPanelConfig.config.file_size)) {
            return false;
        }
    } catch (e) {
        //IE8提示调低安全级别
        Ext.toast({
            html: '<div style="text-align: center;">如果您使用的IE8浏览器，请调低安全级别并且启用安全设置:ActiveX控件和插件-对未标记为可安全执行脚本的ActiveX控件初始化并执行脚本!</div>',
            closable: false,
            align: 't',
            slideInDuration: 400,
            hideDuration: 2000,
            minWidth: 400
        });
    }
    var maxlimit = uploadPanelConfig.config.file_size;//文件大小最大值
    var minlimit = 0;//文件大小最小值
    //获取校验文件大小
    if (typeof record.data.IS_LIMITSIZE != 'undefined' && record.data.IS_LIMITSIZE != null && record.data.IS_LIMITSIZE != 0) {
        maxlimit = record.data.MAXLIMIT;//从附件规则获取文件大小限制
        minlimit = record.data.MINLIMIT;//从附件规则获取文件大小限制
    }
    var busi_id = uploadPanelConfig.config.busiId;
    if (typeof busi_id == 'undefined' || busi_id == null || busi_id.length <= 0) {
        Ext.Msg.alert('提示', '附件缺失唯一标识！');
    }
    /*if(btn.files[0].name.length > 100){
    	Ext.MessageBox.alert("提示", "上传失败，文件名称长度超过限制！");
    	return;
    }*/
    //创建进度条
    Ext.MessageBox.show({
        msg: '正在上传附件,请耐心等待...',
        progressText: '正在上传...',
        width: 300,
        wait: {
            interval: 300
        },
        animateTarget: btn
    });
    UploadPanel.saveExtraField(itemId); // 保存自定义数据
    //判断浏览器版本是否是IE8，如果是，且上传图片，调用压缩图片方法
    if (browserInfo["browser"] != "IE" || (browserInfo["version"] != "8.0" && browserInfo["version"] != "9.0")) {
        var forms = btn.files[0].name.split(".")[btn.files[0].name.split(".").length - 1].toLowerCase();
        if (forms == "png" || forms == "jpg" || forms == "jpeg") {
            var size;
            getSystemSize(function (data) {
                size = data;
            });
            if (size != 0) {
                uploadImage(btn, forms);
                return false;
            }
        }
    }
    var rule_id = record.data.RULE_ID;
    //将附件规则id，业务id，最大值吸入form，提交传到后端
    var form = $('form#' + (formId ? formId : 'uploadpanel-' + itemId + '-uploadform-' + rowIndex));
    form.find('input[name=ruleId]').val(rule_id);
    form.find('input[name=busiId]').val(busi_id);
    form.find('input[name=maxlimit]').val(maxlimit);
    $('form#' + (formId ? formId : 'uploadpanel-' + itemId + '-uploadform-' + rowIndex)).ajaxSubmit({
        url: '/report/third-api/upload/file',
        type: 'POST',
        dataType: 'json',
        data: {
            'browser': browserInfo.browser,
            'version': browserInfo.version,
            busiType: uploadPanelConfig.config.busiType,
            busiProperty: uploadPanelConfig.config.busiProperty
        },
        resetForm: true,
        clearForm: true,
        success: function (data) {
            if (data.code == 20000) {
                Ext.MessageBox.hide();
                //提示上传成功
                Ext.toast({
                    html: '<div style="text-align: center;">上传成功!</div>',
                    closable: false,
                    align: 't',
                    slideInDuration: 400,
                    minWidth: 400
                });
                DSYGrid.getGrid(itemId).getStore().load();
            } else {
                Ext.MessageBox.hide();
                Ext.Msg.alert('提示', "保存失败！" + data.message);
                DSYGrid.getGrid(itemId).getStore().load();
            }
        }
    });
    return false;
};
/**
 * 对上传文件类型进行校验
 * @param btn 上传按钮
 * @param record 上传行记录
 * @param file_type 系统参数文件类型
 * @returns {boolean} 是否通过校验
 */
UploadPanel.checkFileType = function (btn, record, file_type) {
    var file_suffix = file_type;//文件类型限制
    //获取校验文件类型
    if (typeof record.data.IS_LIMITTYPE != 'undefined' && record.data.IS_LIMITTYPE != null && record.data.IS_LIMITTYPE != 0) {
        file_suffix = record.data.FILE_SUFFIX;//从附件规则获取文件类型限制
    }
    /**
     * 校验文件类型
     */
    if (file_suffix != null && file_suffix != '') {
        //获取上传文件的后缀名
        var filePath = $(btn).val();
        var fileExt = filePath.substring(filePath.lastIndexOf(".")).toLowerCase();
        //上传文件与数据库中的文件格式比较
        var flag = file_suffix.toLowerCase().indexOf(fileExt);
        if (flag == null || flag < 0) {
            //TODO 清空文件input
            Ext.Msg.alert('提示', '文件类型错误,请选择文件' + file_suffix);
            return false;
        }
    }
    return true;
};
/**
 * 对上传文件大小进行校验
 * @param btn 上传按钮
 * @returns {boolean} 是否通过校验
 */
UploadPanel.checkFileSize = function (btn, record, file_size) {
    var maxlimit = file_size;//文件大小最大值
    var minlimit = 0;//文件大小最小值
    //获取校验文件大小
    if (typeof record.data.IS_LIMITSIZE != 'undefined' && record.data.IS_LIMITSIZE != null && record.data.IS_LIMITSIZE != 0) {
        maxlimit = record.data.MAXLIMIT;//从附件规则获取文件大小限制
        minlimit = record.data.MINLIMIT;//从附件规则获取文件大小限制
    }
    /**
     * 校验文件大小
     */
    if (maxlimit != null && maxlimit != '') {
        var fileSize = getFileSize(btn);
        // 允许上传不大于20M的文件
        if (fileSize > maxlimit) {
            //TODO 清空file内容
            Ext.Msg.alert('提示', '文件太大，请选择小于' + maxlimit + 'KB的文件！');
            return false;
        }
        if (fileSize < minlimit) {
            //TODO 清空file内容
            Ext.Msg.alert('提示', '文件太小，请选择大于' + minlimit + 'KB的文件！');
            return false;
        }
    }
    return true;
    /**
     * 计算文件大小，返回文件大小值，单位K
     * @param target
     * @returns {number}
     */
    function getFileSize(target) {
        var isIE = /msie/i.test(navigator.userAgent) && !window.opera;
        var fs = 0;
        if (isIE && !target.files) {//如果是ie浏览器，使用ActiveXObject控件判断大小，不支持IE8
            var filePath = target.value;
            var fileSystem = new ActiveXObject("Scripting.FileSystemObject");
            var file = fileSystem.GetFile(filePath);
            fs = file.Size;
        } else if (target.files && target.files.length > 0) {//非IE浏览器判断大小
            fs = target.files[0].size;
        } else {
            fs = 0;
        }
        if (fs > 0) {
            fs = fs / 1024;
        }
        return fs;
    }
};
/**
 * 删除附件
 * @param fileId 附件id
 * @param rule_id 规则id
 * @param file_name 附件名称
 * @param itemId 表格itemId
 * @param itemId 当前行
 * @return {boolean}
 */
UploadPanel.deleteFile = function (fileId, rule_id, file_name, itemId, rowIndex) {
    if (typeof file_name == 'undefined' || file_name == null || file_name == '' || file_name.toLowerCase() == 'undefined' || file_name.toLowerCase() == 'null') {
        file_name = '';
    }
    if (typeof fileId == 'undefined' || fileId == null || fileId == '' || fileId.toLowerCase() == 'undefined' || fileId.toLowerCase() == 'null') {
        if (typeof rule_id == 'undefined' || rule_id == null || rule_id == '' || rule_id.toLowerCase() == 'undefined' || rule_id.toLowerCase() == 'null') {
            //无文件、无规则，直接删除行
            DSYGrid.getGrid(itemId).getStore().removeAt(rowIndex);
            return false;
        } else {
            //无文件，有规则，不做删除
            return false;
        }
    }
    Ext.Msg.confirm('提示', '是否删除附件 ' + file_name, function (btn) {
        if (btn == 'yes') {
            //发送请求:删除当前附件
            Ext.Ajax.request({
                method: 'DELETE',
                url: '/report/third-api/uploadFile/deleteFile',
                params: {
                    fileIdArray: Ext.util.JSON.encode([{FILE_ID: fileId}])
                },
                success: function (response) {
                    var responseJson = Ext.JSON.decode(response.responseText);
                    if (responseJson.success) {
                        //提示删除成功
                        Ext.toast({
                            html: '<div style="text-align: center;">删除成功!</div>',
                            closable: false,
                            align: 't',
                            slideInDuration: 400,
                            minWidth: 400
                        });
                    } else {
                        Ext.Msg.alert('提示', '删除失败 ' + responseJson.message);
                    }
                    if (typeof itemId != 'undefined' && itemId != null && itemId != '') {
                        DSYGrid.getGrid(itemId).getStore().load();
                    }
                }
            });
        }
    });
};
/**
 * 下载附件
 */
UploadPanel.downloadFile = function (file_id) {
    if (typeof(file_id) != "undefined" && file_id != '' && file_id != 0) {
        //向后台传递变更数据信息
        Ext.Ajax.request({
            method: 'GET',
            url: "/report/third-api/uploadFile/queryFileIsExist",
            params: {
                fileId: file_id
            },
            success: function (form, action) {
                var data = Ext.util.JSON.decode(form.responseText);
                if (!data) {
                    Ext.Msg.alert('提示', "下载失败！" + data.message);
                } else {
                    // window.location.href = '/report/third-api/downloadFile?fileId=' + file_id;
                    downloadPublicFiles('/report/third-api/downloadFile', "GET", {
                        fileId:file_id
                    })
                }
            },
            failure: function (form, action) {
                Ext.Msg.alert('提示', "下载失败！" + action.result ? action.result.message : '无返回响应');
            }
        });
    } else {
        Ext.Msg.alert('提示', '该附件尚未上传！');
    }
    //阻止超链接
    return false;
};
/**
 * 表格创建方法
 */
UploadPanel.createGrid = function (config) {
    return new UploadPanel(config).create(config);
};

/**
 * 表格获取方法
 */
UploadPanel.getConfig = function (itemId) {
    return DSYWidget.Manager.grid[itemId];
};
/**
 * 前台校验：必传附件是否全部上传
 */
UploadPanel.validateGrid = function (itemId) {
    if (typeof itemId == 'undefined') {
        itemId = 'UploadGrid';
    }
    var grid = Ext.ComponentQuery.query('grid#' + itemId)[0];
    var flag = true;
    grid.getStore().each(function (record) {
        //当为必选项，并且file_id为空的时候，行背景色为淡黄色
        var fild_id = record.get("FILE_ID");
        if (record.get('NULLABLE') == 'N' && (typeof(fild_id) == "undefined" || fild_id == null || fild_id == '' || fild_id == 'null' || fild_id == '0')) {
            flag = false;
        }
    });
    return flag;
};
/**
 * 后台校验：必传附件是否全部上传
 * @param busiId 业务ID
 * @param busiType 业务类型
 * @param busiProperty 业务规则
 * @return boolean true:通过校验，false：未通过校验
 */
UploadPanel.validateNeed = function (busiId, busiType, busiProperty) {
    var flag = true;
    $.ajax({
            url: '',
            data: {},
            async: false,
            success: function (data) {

            }
        }
    );
    return flag;
};
/**
 * 清除已上传附件
 * @param busi_id 业务Id
 * @param callback 回调函数
 */
UploadPanel.clearFile = function (busi_id, callback) {
    //发送请求:删除当前附件
    Ext.Ajax.request({
        url: '/report/sys-manage/clearFile',
        params: {
            BUSI_ID: busi_id
        },
        success: function (response) {
            var responseJson = Ext.JSON.decode(response.responseText);
            if (Ext.isFunction(callback)) {
                callback(responseJson);
            }
        }
    });
};
/**
 * 上传非IE8图片，进行压缩
 * @param input
 */
//获取系统参数
function getSystemSize(callback) {
    $.ajax({
        url: '/report/third-api/api/sys-data/FILE_PIC_SAVE_SIZE',
        type: 'get',
        data: {},
        async: false,
        success: function (data) {
            var result = eval('(' + data + ')');
            callback(result.FILE_PIC_SAVE_SIZE);
        }
    });
}
function uploadImage(input, forms) {
    var file = input.files[0];
    var fileName = file.name;
    imageCompress(forms, file, function (blob) {
        upload(blob, fileName, input);
    });
};

function imageCompress(forms, file, callback) {
    fileToDataURL(file, function (dataURL) {
        return dataURLToImage(dataURL, function (img) {
            return transform(forms, img);
        })
    });

    function fileToDataURL(file, callback) {
        var reader = new FileReader();
        reader.onload = function () {
            var result = this.result;
            callback(result);
        }
        reader.readAsDataURL(file);
    };

    function dataURLToImage(dataURL, callback) {
        var img = new Image();
        img.onload = function () {
            callback(img);
        }
        img.src = dataURL;
    };

    function transform(forms, img) {
        var dataUrl = compress(forms, img);
        var blob = dataUrlToBlob(forms, dataUrl);

        callback(blob);
        return blob;
    };

    function compress(forms, img) {
        var canvas = document.createElement('canvas');
        var size;
        getSystemSize(function (data) {
            size = data;
        });
        width = img.width;
        height = img.height;
        if (width > height && width > size) {
            height = height * size / width;
            width = size;
        } else if (height > width && height > size) {
            width = width * size / height;
            height = size;
        }
        canvas.width = width;
        canvas.height = height;

        var context = canvas.getContext('2d');
        context.drawImage(img, 0, 0, width, height);
        var dataUrl = canvas.toDataURL('image/' + forms, 0.9);

        return dataUrl;
    };

    function dataUrlToBlob(forms, dataUrl) {
        var text = window.atob(dataUrl.split(",")[1]);
        var buffer = new ArrayBuffer(text.length);
        var ubuffer = new Uint8Array(buffer);

        for (var i = 0; i < text.length; i++) {
            ubuffer[i] = text.charCodeAt(i);
        }

        var type = 'image/' + forms;

        var blob = new window.Blob([buffer], {type: type});

        return blob;
    };
};
function upload(blob, name, btn) {
    var formData = new FormData();
    formData.append('file', blob, name);
    formData.append('size', blob.size);
    var itemId = $(btn).attr('itemid');
    var rowIndex = $(btn).attr('rowindex');
    var uploadPanelConfig = UploadPanel.getConfig(itemId);
    var record = DSYGrid.getGrid(itemId).getStore().getAt(rowIndex);
    var busi_id = uploadPanelConfig.config.busiId;
    var rule_id = "";
    if (record) {
        rule_id = record.data.RULE_ID;
    }
    var maxlimit = uploadPanelConfig.config.file_size;//文件大小最大值
    var browserInfo = getBrowserInfo();
    formData.append("ruleId", rule_id);
    formData.append("busiId", busi_id);
    formData.append("maxlimit", maxlimit);
    formData.append("browser", browserInfo.browser);
    formData.append("version", browserInfo.version);
    formData.append("busiType", uploadPanelConfig.config.busiType);
    formData.append("busiProperty", uploadPanelConfig.config.busiProperty);
    $.ajax({
        url: '/report/third-api/upload/file',
        type: 'POST',
        data: formData,
        resetForm: true,
        clearForm: true,
        processData: false,  //必须false才会避开jQuery对 formdata 的默认处理
        contentType: false,  //必须false才会自动加上正确的Content-Type
        success: function (data) {
            var result = eval('(' + data + ')');
            if (result.data.length==32) {
                Ext.MessageBox.hide();
                //提示上传成功
                Ext.toast({
                    html: '<div style="text-align: center;">上传成功!</div>',
                    closable: false,
                    align: 't',
                    slideInDuration: 400,
                    minWidth: 400
                });
                DSYGrid.getGrid(itemId).getStore().load();
            } else {
                Ext.MessageBox.hide();
                Ext.Msg.alert('提示', "保存失败！" + data.message);
                DSYGrid.getGrid(itemId).getStore().load();
            }
        }
    });
};

//表格的字段配置附件上传
function uploadFileCellItem(map){
    var busiId = map["busiId"];
    var busiType = map["busiType"];
    var busiProperty = map["busiProperty"];
    var editAble = map["editable"];
    if(!busiId){
        return null;
    }
    var editable = (typeof editAble!="undefined" && !editAble) ? editAble : true;
    //判断busiId是否存在
    $.get("/report/third-api/uploadFile/list", {
        busiId: busiId,
        busiType: busiType,
        busiProperty: busiProperty
    }, function(result) {
        var dt = $.parseJSON(result.data);
        var list = dt.list;
        var elements = document.getElementById("fileCell_"+busiId);
        if(list.length==0){ //不存在，上传
            if(editable){
                elements.innerHTML = '<div class="uploadpanel-btn uploadpanel-btn-upload" style="float: right;">' +
                    '<form id="fromCell_'+busiId+'" enctype="multipart/form-data">' +
                    ' <input type="file" name="file" onchange="cellUploadFile(this,\''+ busiId +'\',\''+ busiType +'\',\''+ busiProperty+'\',\''+ editable+'\')" ' +
                    ' style="filter:alpha(opacity:0);opacity:0;width:100%;cursor: pointer;font-size: 0;height: 100%;"/></form></div>';
            }
        } else { //存在：下载、删除
            var data = list[0];
            if(data.FILE_ID != null){ //已有附件
                var icon = '<image src="/report/image/file/docx.png">';
                const type_img = ['doc', 'docx', 'jpeg', 'jpg', 'pdf','png', 'ppt', 'pptx', 'rar', 'txt', 'xls', 'xlsx', 'zip'];
                var fileType = data.FILE_NAME.substring(data.FILE_NAME.lastIndexOf(".")+1);
                if(type_img.includes(fileType)){
                    icon = '<image src="/report/image/file/'+fileType+'.png">';
                }
                var deletebtn = !editable ? "" : '<div style="float: right;margin-left: 5px;" class="uploadpanel-btn uploadpanel-btn-delete" ' +
                        'onclick="deleteCellFile(\''+data.FILE_ID+'\',\''+data.FILE_NAME+'\',\''+busiId +'\',\''+ busiType +'\',\''+ busiProperty +'\',\''+ editable +'\')"></div>';
                elements.innerHTML = '<a style="color:#3329ff;display: inline-block;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;' +
                    'cursor: pointer;'+(!editable?"width: 80%;":"width: 70%;")+'"' +
                    'onclick="downloadCellFile(\''+data.FILE_ID+'\')">' + icon + data.FILE_NAME +'</a>' +
                    deletebtn + '<div class="uploadpanel-btn uploadpanel-btn-download" style="float: right;margin-left: 5px;" onclick="downloadCellFile(\''+data.FILE_ID+'\')"></div>';
                //添加鼠标移入、移出事件
                $("#fileCell_"+busiId).mousemove(function(e) {
                    cellFileInfoShow(data.FILE_NAME,data.FILE_DESC,data.FILE_SIZE,data.UPLOAD_TIME);
                    var xx = e.originalEvent.x || e.originalEvent.layerX || 0;
                    var yy = (e.originalEvent.y || e.originalEvent.layerY || 0);
                    if(document.getElementById("fileCellInfoDiv")){
                        document.getElementById("fileCellInfoDiv").style.left = xx + 15;
                        document.getElementById("fileCellInfoDiv").style.top = yy + 18;
                        document.getElementById("fileCellInfoDiv").style.display = "block";
                    }
                });
                elements.parentElement.parentElement.setAttribute("onmouseout","cellFileInfoClose(\'"+busiId+"\')");
            } else{ //没有附件
                var updateBtn = !editable ? "" : ' <div class="uploadpanel-btn uploadpanel-btn-upload" style="float: right;">' +
                    ' <form id="fromCell_'+busiId+'" enctype="multipart/form-data">' +
                    ' <input type="file" name="file" onchange="cellUploadFile(this,\''+ busiId +'\',\''+ busiType +'\',\''+ busiProperty +'\',\''+ editable +'\',\''+ data.RULE_ID
                    +'\',\''+ data.IS_LIMITTYPE+'\',\''+ data.FILE_SUFFIX+'\',\''+ data.IS_LIMITSIZE +'\',\''+ data.MAXLIMIT +'\',\''+ data.MINLIMIT  +'\')" ' +
                    ' style="filter:alpha(opacity:0);opacity:0;width:100%;cursor: pointer;font-size: 0;height: 100%;"/></form></div>';
                elements.innerHTML = (data.FILE_DESC!=null ? "<div style='display: inline-block;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;width: 80%'>"+data.FILE_DESC+"</div>" : '') + updateBtn;
            }
        }
    }, "json");
    return "<div id='fileCell_"+busiId+"'></div>";
}

//表格的单元格文件上传
function cellUploadFile(self, busiId, busiType, busiProperty, editable , ruleId, isLimitType, fileSuffix, isLimitSize, maxLimit, minLimit) {
    //创建进度条
    Ext.MessageBox.show({
        msg: '正在上传附件,请耐心等待...',
        progressText: '正在上传...',
        width: 300,
        wait: {
            interval: 300
        },
        animateTarget: self
    });
    //获取校验文件类型
    var file_suffix = (!!getSysParam('DEBT_FILE_TYPE') ? getSysParam('DEBT_FILE_TYPE') : ".doc/.docx/.pdf/.jpg/.jpeg/.png");//文件类型限制
    if (typeof isLimitType != 'undefined' && isLimitType != null && isLimitType != 0) {
        file_suffix = fileSuffix;//从附件规则获取文件类型限制
    }
    if (file_suffix != null && file_suffix != '') {
        //获取上传文件的后缀名
        var filePath = $(self).val();
        var fileExt = filePath.substring(filePath.lastIndexOf(".")).toLowerCase();
        //上传文件与数据库中的文件格式比较
        var flag = file_suffix.toLowerCase().indexOf(fileExt);
        if (flag == null || flag < 0) {
            Ext.Msg.alert('提示', '文件类型错误,请选择文件' + file_suffix);
            return false;
        }
    }
    //获取校验文件大小
    var maxlimit = (!!getSysParam('DEBT_FILE_SIZE') ? getSysParam('DEBT_FILE_SIZE') : 1024 * 1024);//文件大小最大值
    var minlimit = 0; //文件大小最小值
    if (typeof isLimitSize != 'undefined' && isLimitSize != null && isLimitSize != 0) {
        maxlimit = maxLimit;//从附件规则获取文件大小限制
        minlimit = minLimit;
    }
    if (maxlimit != null && maxlimit != '') {
        var fileSize = getFileSize(self);
        if (fileSize > maxlimit) {
            Ext.Msg.alert('提示', '文件太大，请选择小于' + maxlimit + 'KB的文件！');
            return false;
        }
        if (fileSize < minlimit) {
            Ext.Msg.alert('提示', '文件太小，请选择大于' + minlimit + 'KB的文件！');
            return false;
        }
    }
    // 上传附件
    $('form#fromCell_'+busiId).ajaxSubmit({
        url: '/report/third-api/uploadFile/file',
        type: 'POST',
        dataType: 'json',
        data: {
            busiId: busiId,
            busiType: busiType,
            busiProperty: busiProperty,
            ruleId: ruleId
        },
        resetForm: true,
        clearForm: true,
        success: function (result) {
            Ext.MessageBox.hide();
            if(result.code==20000){
                var data =JSON.parse(result.data);
                if(data.success){
                    //提示上传成功
                    Ext.toast({
                        html: '<div style="text-align: center;">上传成功!</div>',
                        closable: false,
                        align: 't',
                        slideInDuration: 400,
                        minWidth: 400
                    });
                    //刷新单元格
                    uploadFileCellItem ({
                        busiId: busiId,
                        busiType: busiType,
                        busiProperty: busiProperty,
                        editable: editable
                    });
                } else {
                    Ext.Msg.alert('提示', "上传失败！");
                }
            }else{
                Ext.Msg.alert('提示', "上传失败！");
            }
        }
    });
}

/**
 * 计算文件大小，返回文件大小值，单位K
 * @param target
 * @returns {number}
 */
function getFileSize(target) {
    var isIE = /msie/i.test(navigator.userAgent) && !window.opera;
    var fs = 0;
    if (isIE && !target.files) {//如果是ie浏览器，使用ActiveXObject控件判断大小，不支持IE8
        var filePath = target.value;
        var fileSystem = new ActiveXObject("Scripting.FileSystemObject");
        var file = fileSystem.GetFile(filePath);
        fs = file.Size;
    } else if (target.files && target.files.length > 0) {//非IE浏览器判断大小
        fs = target.files[0].size;
    } else {
        fs = 0;
    }
    if (fs > 0) {
        fs = fs / 1024;
    }
    return fs;
}

//表格的单元格文件删除
function deleteCellFile(fileId, fileName, busiId, busiType, busiProperty, editable){
    Ext.Msg.confirm('提示', '是否删除附件 ' + fileName, function (btn) {
        if (btn == 'yes') {
            //发送请求:删除当前附件
            $.ajax({
                url: '/report/third-api/uploadFile/deleteFileSingle',
                type: 'DELETE',
                data: {fileId : fileId},
                success: function (res) {
                    if (res.code == 20000) {
                        //提示上传成功
                        Ext.toast({
                            html: '<div style="text-align: center;">删除成功!</div>',
                            closable: false,
                            align: 't',
                            slideInDuration: 400,
                            minWidth: 400
                        });
                        //刷新单元格
                        var elements = document.getElementById("fileCell_"+busiId);
                        $("#fileCell_"+busiId).unbind("mousemove");
                        elements.parentElement.parentElement.removeAttribute("onmouseout");
                        document.getElementById("fileCellInfoDiv").remove();
                        uploadFileCellItem ({
                            busiId: busiId,
                            busiType: busiType,
                            busiProperty: busiProperty,
                            editable: editable
                        });
                    } else {
                        Ext.Msg.alert('提示', res.msg);
                    }
                }
            });
        }
    });
}

//表格的单元格文件下载
function downloadCellFile(fileId){
    // window.location.href = '/report/third-api/downloadFile?fileId=' + fileId;
    downloadPublicFiles('/report/third-api/downloadFile',"GET",{
        fileId:fileId
    })
}

//显示单元附件信息
function cellFileInfoShow(fileName, fileDesc, fileSize, time){
    //鼠标移上去的附件信息
    if(!document.getElementById("fileCellInfoDiv")) {
        var infoDiv = document.createElement("div");
        infoDiv.setAttribute("id", "fileCellInfoDiv");
        infoDiv.setAttribute("class", "x-tip x-layer x-tip-default x-border-box")
        infoDiv.setAttribute("style", "z-index: 19001;background-color: rgb(255, 255, 204);display: none;");
        top.document.body.append(infoDiv);
        var infoSpan1 = document.createElement("span");
        infoSpan1.setAttribute("id","cellFileName");
        var infoSpan2 = document.createElement("span");
        infoSpan2.setAttribute("id","cellFileDesc");
        var infoSpan3 = document.createElement("span");
        infoSpan3.setAttribute("id","cellFileSize");
        var infoSpan4 = document.createElement("span");
        infoSpan4.setAttribute("id","cellFileUploadTime");
        infoDiv.append(infoSpan1);
        infoDiv.append(infoSpan2);
        infoDiv.append(infoSpan3);
        infoDiv.append(infoSpan4);
    }
    if(!!document.getElementById("fileCellInfoDiv")){
        //隐藏原有的tip
        if(document.getElementsByClassName("x-layer x-tip-default x-border-box")){
            var doc = document.getElementsByClassName("x-layer x-tip-default x-border-box");
            for(var i=0; i< doc.length; i++){
                document.getElementsByClassName("x-layer x-tip-default x-border-box").item(i).style.display = "none";
            }
            if(document.getElementsByClassName("x-css-shadow").item(0)){
                document.getElementsByClassName("x-css-shadow").item(0).style.display = "none";
            }
        }
        //显示添加的tip
        document.getElementById("cellFileName").innerHTML = "文件名称：" + fileName +"<br />";
        if(fileDesc!=null && fileDesc!="null"){
            document.getElementById("cellFileDesc").innerHTML = "文件说明：" + fileDesc +"<br />";
        }
        document.getElementById("cellFileSize").innerHTML = "文件大小：" + fileSize +"<br />";
        document.getElementById("cellFileUploadTime").innerHTML = "上传时间：" + time;
    }
}

//隐藏单元附件信息
function cellFileInfoClose(){
    if(document.getElementById("fileCellInfoDiv")){
        document.getElementById("fileCellInfoDiv").style.display = "none";
    }
}
